package com.ericsson.enap.modules.monitor.service.impl;

import com.ericsson.enap.modules.monitor.entity.*;
import com.ericsson.enap.modules.monitor.mapper.CabSwitchInterfaceMapper;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.topology.entity.CabSwitch;
import com.ericsson.enap.modules.monitor.mapper.CabSwitchMapper;
import com.ericsson.enap.modules.sys.mapper.EpcDictMapper;
import com.ericsson.enap.modules.monitor.mapper.SysDictDataMapper;
import com.ericsson.enap.modules.monitor.service.SwitchDBDataService;
import com.ericsson.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SwitchDBDataServiceImpl implements SwitchDBDataService {
    @Autowired
    private CabSwitchMapper cabSwitchMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private CabSwitchInterfaceMapper cabSwitchInterfaceMapper;

    @Autowired
    private EpcDictMapper epcDictMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static String CAB_MONGO_TIME="CAB_MONGO_TIME";


    @Override
    public List<CabSwitch> getSwitchList() {
        return cabSwitchMapper.selectCabSwitch();
    }

    public Map<String, String> getSysDictData(){
        List<SysDictData> sysDictDataList= sysDictDataMapper.selectDictDataByType("cab_switch_interface");
        return sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictLabel,SysDictData::getDictValue, (key1, key2) -> key2));
    }

    @Override
    public void insertSwitchTotalList(List<SwitchTotalData> switchTotalDataList) {
        String collectionName="cab_monitor_switch";
        if(mongoTemplate.collectionExists(collectionName)) {
            mongoTemplate.dropCollection(collectionName);
        }
        mongoTemplate.createCollection(collectionName);
        mongoTemplate.insert(switchTotalDataList,collectionName);
    }

    @Override
    public void insertSwitchPortDataList(List<SwitchPortData> switchPortDataList,String programDate) {
        String collectionName="cab_monitor_"+programDate.substring(0,10).replace("-","")+"_switch";
        if(!mongoTemplate.collectionExists(collectionName)) {
            mongoTemplate.createCollection(collectionName);
        }
        mongoTemplate.insert(switchPortDataList,collectionName);
        this.dropPastCollection();
    }

    @Override
    public void insertSwitchInterStatus(List<SwitchInterfaceStatus> switchInterfaceStatusList) {
        cabSwitchInterfaceMapper.truncateSwitchStatus();
        this.batchInsertJDBC(switchInterfaceStatusList);
    }

    @Override
    public Map<String,SwitchPortData> getBeforeMinuteData(String beforeData) {
        List<SwitchPortData> switchPortDataList=mongoTemplate.find(new Query(Criteria.where("programTime").is(beforeData)),SwitchPortData.class,"cab_monitor_"+beforeData.substring(0,10).replace("-","")+"_switch");
        Map<String,SwitchPortData> stringSwitchPortDataMap=switchPortDataList.stream().collect(Collectors.toMap(k ->k.getSwitchName()+":"+k.getPortName(),SwitchPortData->SwitchPortData));
        return stringSwitchPortDataMap;
    }

    public void dropPastCollection(){
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName(CAB_MONGO_TIME);
        epcDict= epcDictMapper.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            String pastDate= DateUtils.getPastDate(Integer.parseInt(epcDict.getKeyValue()),"yyyyMMdd");
            if(mongoTemplate.collectionExists("cab_monitor_"+pastDate+"_switch")) {
                mongoTemplate.dropCollection("cab_monitor_"+pastDate+"_switch");
            }
        }
    }

    @Transactional("dbTransaction")
    public void batchInsertJDBC(List<SwitchInterfaceStatus> switchInterfaceStatusList) throws DataAccessException {
        int pointsDataLimit = 500;//限制条数
        Integer size = switchInterfaceStatusList.size();
        //判断是否有必要分批
        if(pointsDataLimit<size){
            int part = size/pointsDataLimit;//分批数　　　　　　//
            for (int i = 0; i < part; i++) {
                //1000条
                List<SwitchInterfaceStatus> listPage = switchInterfaceStatusList.subList(0, pointsDataLimit);
                batchInsertSQL(listPage);
                //剔除
                switchInterfaceStatusList.subList(0, pointsDataLimit).clear();
            }
            if(!switchInterfaceStatusList.isEmpty()){
                batchInsertSQL(switchInterfaceStatusList);
            }
        }else{
            batchInsertSQL(switchInterfaceStatusList);
        }
    }

    private void batchInsertSQL(List<SwitchInterfaceStatus> switchInterfaceStatusList){
        StringBuffer sqlbuf = new StringBuffer()
                .append("insert into epc_cab_switch_status (switch_name, switch_interface, original_interface, interface_flag) values ");
        MessageFormat form = new MessageFormat("(''{0}'',''{1}'', ''{2}'', ''{3,number,#}''),");
        for (SwitchInterfaceStatus sis : switchInterfaceStatusList) {
            Object[] args = {sis.getSwitchName(),sis.getSwitchInterface(),sis.getOriginalInterface(),sis.getSwitchStatus()};
            sqlbuf.append(form.format(args));
        }
        String sql = sqlbuf.toString();
        sql = sql.substring(0, sql.length()-1);
        jdbcTemplate.update(sql);
    }
}
